﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using IRC.IRepairClouds.DataLayer;
using IRC.IRepairClouds.DataLayer.Cache;
using IRC.IRepairClouds.WebClient.DataObjects;
using Telerik.Web.UI;
using System.Linq.Expressions;

namespace IRC.IRepairClouds.WebClient.ws
{
    /// <summary>
    /// Summary description for Global
    /// </summary>
    [WebService(Namespace = "http://app.irepairmanager.eu/webservices")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class Cases : System.Web.Services.WebService
    {
        [WebMethod]
        public object Customer_Get()
        {
            Auth.Check(PagesAuthorization.Pages.NewCase, Auth.AuthType.SecurityException);

            using (ICloudRepairEntities db = new ICloudRepairEntities())
            {
                var userData = CacheManager.Users.Current;
                var Customers = (from cus in db.Customers
                                 where cus.PartnerId == userData.PartnerGuid
                                 select new 
                                 {
                                     GuidId = cus.GuidId,
                                     Name = cus.Name,
                                     Surname = cus.Surname,
                                     Phone = cus.Phone,
                                     Email = cus.Email,
                                     Description = cus.Description,
                                     FullName = cus.Name + " " + cus.Surname + " " + cus.Email + " " + cus.Phone
                                 });
                var cust = Customers.ToList();
                return cust;
            }
        }

        [WebMethod]
        public object Customer_Find(
            string firstName,
            string surName,
            string email,
            string phone)
        {
            Auth.Check(PagesAuthorization.Pages.NewCase, Auth.AuthType.SecurityException);

            using (ICloudRepairEntities db = new ICloudRepairEntities())
            {
                var userData = CacheManager.Users.Current;
                var cust = (from cus in db.Customers
                                 where cus.PartnerId == userData.PartnerGuid
                                 && cus.Name == firstName
                                 && cus.Surname == surName
                                 && cus.Email == email
                                 && cus.Phone ==phone
                                 select new
                                 {
                                     GuidId = cus.GuidId
                                 }).FirstOrDefault();

                return cust;
            }
        }


        [WebMethod]
        public object PhoneSets_Get()
        {
            Auth.Check(PagesAuthorization.Pages.NewCase, Auth.AuthType.SecurityException);

            using (ICloudRepairEntities db = new ICloudRepairEntities())
            {
                var PhoneSets = (from ps in db.PhoneSet
                                 select new
                                 {
                                     Id = ps.Id,
                                     Name = ps.Name,

                                 });
                var psets = PhoneSets.ToList();
                return psets;
            }
        }


        [WebMethod]
        public object FastProblem_Get()
        {
            Auth.Check(PagesAuthorization.Pages.NewCase, Auth.AuthType.SecurityException);

            using (ICloudRepairEntities db = new ICloudRepairEntities())
            {
                var FastProblems = (from fp in db.Fast_Problem
                                 select new
                                 {
                                     Id = fp.ID,
                                     Name = fp.Problem,

                                 });
                var fprob = FastProblems.ToList();
                return fprob;
            }
        }

        [WebMethod]
        public object Manufacturer_Get(RadComboBoxContext context)
        {
            Auth.Check(PagesAuthorization.Pages.NewCase, Auth.AuthType.SecurityException);

            List<RadComboBoxItemData> result = new List<RadComboBoxItemData>(context.NumberOfItems);
            RadComboBoxData comboData = new RadComboBoxData();

            using (ICloudRepairEntities db = new ICloudRepairEntities())
            {

                if (context.Text != string.Empty)
                {
                    var Manuf = (from man in db.EManufacturer
                                  select new
                                  {
                                      Id = man.ManufacturerGuid,
                                      Name = man.Name
                                  }).Where(man => man.Name.Contains(context.Text));

                    string[] criteria = context.Text.Split(' ');


                    var data = Manuf.ToList();

                    try
                    {

                        int itemsPerRequest = 10;
                        int itemOffset = context.NumberOfItems;
                        int endOffset = itemOffset + itemsPerRequest;
                        if (endOffset > data.Count)
                        {
                            endOffset = data.Count;
                        }
                        if (endOffset == data.Count)
                        {
                            comboData.EndOfItems = true;
                        }
                        else
                        {
                            comboData.EndOfItems = false;
                        }
                        result = new List<RadComboBoxItemData>(endOffset - itemOffset);
                        for (int i = itemOffset; i < endOffset; i++)
                        {
                            RadComboBoxItemData itemData = new RadComboBoxItemData();
                            itemData.Text = data[i].Name;
                            itemData.Value = data[i].Id.ToString();

                            result.Add(itemData);
                        }

                        if (data.Count > 0)
                        {
                            comboData.Message = String.Format("Items <b>1</b>-<b>{0}</b> out of <b>{1}</b>", endOffset.ToString(), data.Count.ToString());
                        }
                        else
                        {
                            comboData.Message = "No matches";
                        }

                    }
                    catch (Exception e)
                    {
                        comboData.Message = e.Message;
                    }
                }
                else
                {
                    comboData.Message = "No matches";
                }

                comboData.Items = result.ToArray();
                return comboData;

            }
        }

        [WebMethod]
        public object Model_Get(RadComboBoxContext context)
        {
            Auth.Check(PagesAuthorization.Pages.NewCase, Auth.AuthType.SecurityException);

            List<RadComboBoxItemData> result = new List<RadComboBoxItemData>(context.NumberOfItems);
            RadComboBoxData comboData = new RadComboBoxData();

            using (ICloudRepairEntities db = new ICloudRepairEntities())
            {

                if (context.Text != string.Empty)
                {
                    var Models = (from mod in db.Model
                                  select new
                                  {
                                      Id = mod.GuidId,
                                      FullName = mod.Manufacturer.Name.Replace(" ", "") + " " + mod.Name.Replace(" ", "")
                                  }).Where(mod => mod.FullName.Contains(context.Text));

                    string[] criteria = context.Text.Split(' ');

                    //var data = Models.Where(m => m.Name.Contains(context.Text)).ToList();
                    //foreach (string cr in criteria)
                    //{
                    //    Models = Models.Where(m => m.Name.Contains(cr.Replace(" ", "")));
                    //}

                    //Models = Models.Where(m => m.FullName.Contains(context.Text));

                    var data = Models.ToList();

                    try
                    {

                        int itemsPerRequest = 10;
                        int itemOffset = context.NumberOfItems;
                        int endOffset = itemOffset + itemsPerRequest;
                        if (endOffset > data.Count)
                        {
                            endOffset = data.Count;
                        }
                        if (endOffset == data.Count)
                        {
                            comboData.EndOfItems = true;
                        }
                        else
                        {
                            comboData.EndOfItems = false;
                        }
                        result = new List<RadComboBoxItemData>(endOffset - itemOffset);
                        for (int i = itemOffset; i < endOffset; i++)
                        {
                            RadComboBoxItemData itemData = new RadComboBoxItemData();
                            itemData.Text = data[i].FullName;
                            itemData.Value = data[i].Id.ToString();

                            result.Add(itemData);
                        }
                        if (result.Count <= 0)
                        {
                            RadComboBoxItemData itemData = new RadComboBoxItemData();
                            itemData.Text = "<Add new item>";
                            itemData.Value = Guid.Empty.ToString();

                            result.Add(itemData);
                            comboData.Text = itemData.Text;
                        }

                        if (result.Count > 0)
                        {
                            comboData.Message = String.Format("Items <b>1</b>-<b>{0}</b> out of <b>{1}</b>", endOffset.ToString(), result.Count.ToString());
                        }
                        //else
                        //{
                        //    comboData.Message = "No matches";
                        //}

                    }
                    catch (Exception e)
                    {
                        comboData.Message = e.Message;
                    }
                }
                else
                {
                    comboData.Message = "No matches";
                }
    
                comboData.Items = result.ToArray();
                return comboData;

            }
        }

        [WebMethod]
        public object Status_Get()
        {
            Auth.Check(PagesAuthorization.Pages.NewCase, Auth.AuthType.SecurityException);

            using (ICloudRepairEntities db = new ICloudRepairEntities())
            {
                var Statuses = (from stat in db.Status
                              select new
                              {
                                  Id = stat.ID,
                                  Name = stat.Name
                              });
                var statList = Statuses.ToList();
                return statList;
            }
        }

        [WebMethod]
        public object CaseType_Get()
        {
            Auth.Check(PagesAuthorization.Pages.NewCase, Auth.AuthType.SecurityException);

            using (ICloudRepairEntities db = new ICloudRepairEntities())
            {
                var CaseTypes = (from ct in db.CaseType
                                    select new
                                    {
                                        Id = ct.CaseTypeId,
                                        Name = ct.Name,

                                    });
                var ctyps = CaseTypes.ToList();
                return ctyps;
            }
        }


        [WebMethod]
        public object DeviceConditions_Get()
        {
            Auth.Check(PagesAuthorization.Pages.NewCase, Auth.AuthType.SecurityException);

            using (ICloudRepairEntities db = new ICloudRepairEntities())
            {
                var DeviceConditions = (from dc in db.DeviceCondition
                                 select new
                                 {
                                     Id = dc.Id,
                                     Name = dc.Name,

                                 });
                var devconds = DeviceConditions.ToList();
                return devconds;
            }
        }

        [WebMethod]
        public object PhoneCondition_Get()
        {
            Auth.Check(PagesAuthorization.Pages.NewCase, Auth.AuthType.SecurityException);

            using (ICloudRepairEntities db = new ICloudRepairEntities())
            {
                var PhoneConds = (from cond in db.DeviceCondition
                                 select new
                                 {
                                     Id = cond.Id,
                                     Name = cond.Name,

                                 });
                var pconds = PhoneConds.ToList();
                return pconds;
            }
        }


        [WebMethod]
        public object Case_GetInitial()
        {
            try
            {
                Auth.Check(PagesAuthorization.Pages.NewCase, Auth.AuthType.SecurityException);
                using (ICloudRepairEntities db = new ICloudRepairEntities())
                {
                    return new WSResult<object>
                    {
                        Success = true,
                        Data = new
                        {
                            CaseId = System.DBNull.Value,
                            CustomerId = System.DBNull.Value,
                            DeviceConditionId = 30,
                            Deposit = 0,
                            Description = string.Empty,
                            EstimatedPrice = 0,
                            IMEI = string.Empty,
                            EstimatedDateCompletion = (DateTime.Now.AddDays(1)).ToClientDateStr(),
                            currentModel = System.DBNull.Value,
                            PhoneSets = new List<int>(),
                            RepairOrderNumber = string.Empty
                        }
                    };
                }

            }
            catch (Exception ex)
            {
                //ExceptionHandling.Handle(ex);
                throw;
            }
        }

        [WebMethod]
        public object Case_GetForEdit(string caseRowGuid, bool isHistory)
        {
            try
            {
                Auth.Check(PagesAuthorization.Pages.NewCase, Auth.AuthType.SecurityException);
                using (ICloudRepairEntities db = new ICloudRepairEntities())
                {
                    var x = db.Case.Where(c => c.CaseId == new Guid(caseRowGuid)).Select(c => new
                    {
                        CaseId = c.CaseId,
                        CustomerId = c.CustomerId,
                        DeviceConditionId = c.DeviceConditionId,
                        Description = c.CaseDescription,
                        c.Deposit,
                        c.EstimatedPrice,
                        c.EstimatedDateCompletion,
                        c.RepairOrderNumber,
                        PhoneSets = c.CrossCasePhoneSet.Select(ps => new
                        {
                            Id = ps.PhoneSetId
                        }),
                        c.IMEI,
                        c.ModelGuid
                    }).FirstOrDefault();
                    if (x == null)
                        return null;

                    var Models = (from mod in db.Model
                                  select new
                                  {
                                      Id = mod.GuidId,
                                      FullName = mod.Manufacturer.Name.Replace(" ", "") + " " + mod.Name.Replace(" ", "")
                                  }).Where(mod => mod.Id==x.ModelGuid).GetSingle();

                    List<int> newPhoneSets = new List<int>();
                    foreach(var val in x.PhoneSets)
                        newPhoneSets.Add(val.Id);
                    return new WSResult<object>
                    {
                        Success = true,
                        Data = new
                        {
                            x.CaseId,
                            x.CustomerId,
                            x.DeviceConditionId,
                            x.Deposit,
                            x.Description,
                            x.EstimatedPrice,
                            x.IMEI,
                            EstimatedDateCompletion = x.EstimatedDateCompletion.ToNullable().ToClientDateStr(),
                            currentModel = Models,
                            PhoneSets = newPhoneSets,
                            x.ModelGuid,
                            x.RepairOrderNumber,
                            isHistory
                        }
                    };
                }

            }
            catch (Exception ex)
            {
                //ExceptionHandling.Handle(ex);
                throw;
            }
        }


        [WebMethod]
        public object CasesImeiHistory_Get(DataObjects.Grid grid, string imei)
        {
            try
            {
                Auth.Check(PagesAuthorization.Pages.NewCase, Auth.AuthType.SecurityException);

                using (ICloudRepairEntities db = new ICloudRepairEntities())
                {
                    var userData = CacheManager.Users.Current;

                    IQueryable<ECase> cases = db.Case.Where(cas => cas.PartnerId == userData.PartnerGuid).Where(i => i.IMEI == imei);
                    IQueryable<ECase> items = cases.OrderByDescending(i => i.RepairOrderNumber); ;
                    items = items.Sort(grid.Sort,
                        items.CreateSortField("CustomerName", i => i.Customer.Name),
                        items.CreateSortField("CustomerSurname", i => i.Customer.Surname),
                        items.CreateSortField("CustomerPhone", i => i.Customer.Phone),
                        items.CreateSortField("Imei", i => i.IMEI),
                        items.CreateSortField("EstimatedPrice", i => i.EstimatedPrice),
                        items.CreateSortField("EstimatedDate", i => i.EstimatedDateCompletion)
                    );
                    var aa = items.ToList();
                    return new
                    {
                        Count = items.Count(),
                        Items = items.Select(c =>
                            new
                            {
                                RowGuid = c.CaseId,
                                RepairOrderNumber = c.RepairOrderNumber,
                                CustomerName = c.Customer.Name,
                                CustomerSurname = c.Customer.Surname,
                                CustomerPhone = c.Customer.Phone,
                                EstimatedPrice = c.EstimatedPrice,
                                EstimatedDateCompletion = c.EstimatedDateCompletion,
                                ProblemDescription = c.CaseDescription.Length > 15 ? c.CaseDescription.Substring(0, 15) + "..." : c.CaseDescription,
                            }).Skip(grid.StartIndex).Take(grid.PageSize).Postprocess(c => new
                            {
                                c.RowGuid,
                                c.RepairOrderNumber,
                                EstimatedDateCompletion = c.EstimatedDateCompletion.CDateToStrDay(),
                                c.CustomerName,
                                c.CustomerSurname,
                                c.CustomerPhone,
                                c.ProblemDescription,
                                c.EstimatedPrice
                            }).ToList()
                    };
                }
            }
            catch (Exception ex)
            {
                //ExceptionHandling.Handle(ex);
                throw;
            }
        }

        [WebMethod]
        public object Cases_Get(DataObjects.Grid grid)
        {
            try {
                Auth.Check(PagesAuthorization.Pages.NewCase, Auth.AuthType.SecurityException);

                using (ICloudRepairEntities db = new ICloudRepairEntities())
                {
                   var userData = CacheManager.Users.Current;

                   IQueryable<ECase> cases = db.Case.Where(cas => cas.PartnerId == userData.PartnerGuid);
                   IQueryable<ECase> items = cases.OrderByDescending(i => i.RepairOrderNumber); ;
                   items = items.Sort(grid.Sort,
                       items.CreateSortField("CustomerName", i => i.Customer.Name),
                       items.CreateSortField("CustomerSurname", i => i.Customer.Surname),
                       items.CreateSortField("CustomerPhone", i => i.Customer.Phone),
                       items.CreateSortField("Imei", i => i.IMEI),
                       items.CreateSortField("EstimatedPrice", i => i.EstimatedPrice),
                       items.CreateSortField("EstimatedDate", i => i.EstimatedDateCompletion)
                   );
                   var aa = items.ToList();
                    return new
                    {
                        Count = items.Count(),
                        Items = items.Select(c =>
                            new
                            {
                                RowGuid =c.CaseId,
                                RepairOrderNumber = c.RepairOrderNumber,
                                CustomerName = c.Customer.Name,
                                CustomerSurname = c.Customer.Surname,
                                CustomerPhone = c.Customer.Phone,
                                EstimatedPrice = c.EstimatedPrice,
                                EstimatedDateCompletion = c.EstimatedDateCompletion,
                                ProblemDescription = c.CaseDescription.Length > 15 ? c.CaseDescription.Substring(0, 15) + "..." : c.CaseDescription,
                            }).Skip(grid.StartIndex).Take(grid.PageSize).Postprocess(c => new
                            {
                                c.RowGuid,
                                c.RepairOrderNumber,
                                EstimatedDateCompletion = c.EstimatedDateCompletion.CDateToStrDay(),
                                c.CustomerName,
                                c.CustomerSurname,
                                c.CustomerPhone,
                                c.ProblemDescription,
                                c.EstimatedPrice
                            }).ToList()
                    };
                }
            }
            catch (Exception ex) {
                //ExceptionHandling.Handle(ex);
                throw;
            }
        }

        [WebMethod]
        public object NewModel_Save(string ExistingManufacturer, string NewManufacturer, string NewModel)
        {
            string FullName = NewManufacturer.Replace(" ", "") + " " + NewModel.Replace(" ", "");
            try
            {
                //TODO
                Auth.Check(PagesAuthorization.Pages.NewCase, Auth.AuthType.SecurityException);
                
                using (var db = new ICloudRepairEntities())
                {
                    Manufacturer manufacturer = new Manufacturer();

                    EModel model = new EModel();
                    model.GuidId = Guid.NewGuid();
                    model.Name = NewModel;

                    if (ExistingManufacturer != null && ExistingManufacturer !=string.Empty)
                    {
                        Guid guid = new Guid(ExistingManufacturer);
                        manufacturer = db.EManufacturer.Where(m => m.ManufacturerGuid == guid).FirstOrDefault();
                        manufacturer.Model.Add(model);
                        FullName = manufacturer.Name.Replace(" ", "") + " " + NewModel.Replace(" ", "");
                    }
                    else
                    {
                        manufacturer.ManufacturerGuid = Guid.NewGuid();
                        manufacturer.Name = NewManufacturer;
                        manufacturer.Model.Add(model);
                        db.AddToEManufacturer(manufacturer);
                    }

                    db.SaveChanges();

                    
                    return new WSResult<object>
                    {
                        Success = true,
                        ErrorMessage = string.Empty,
                        Data = new
                        {
                            Id = model.GuidId,
                            FullName = FullName
                        }
                    };

                }

            }
            catch (Exception ex)
            {
                return new WSResult<object>
                {
                    Success = false,
                    ErrorMessage = ex.Message,
                    Data = new
                    {
                        Id = System.DBNull.Value,
                        FullName = FullName
                    }
                };
            }
        }

        [WebMethod]
        public object Customer_Save(string guid, string name, string surname, string phone, string email)
        {
            try {
                //TODO
                Auth.Check(PagesAuthorization.Pages.NewCase, Auth.AuthType.SecurityException);

                using (var db = new ICloudRepairEntities()) {

                    if (guid !=string.Empty)
                    {
                        Guid existingGuid = Guid.Parse(guid);
                        ECustomer cust = (from c in db.Customers
                                           where c.GuidId == existingGuid
                                    select c).FirstOrDefault()
                                   ;
                        cust.Name = name;
                        cust.Surname = surname;
                        cust.Phone = phone;
                        cust.Email = email;
                    }
                    else
                    {
                        ECustomer cust = new ECustomer();
                        cust.GuidId = Guid.NewGuid();
                        var userData = CacheManager.Users.Current;
                        cust.PartnerId = userData.PartnerGuid;
                        cust.Name = name;
                        cust.Surname = surname;
                        cust.Phone = phone;
                        cust.Email = email;
                        db.AddToCustomers(cust);
                    }
                    db.SaveChanges();
                }
                return true;
            }
            catch (Exception ex) {
                ex.Data["name"] = name;
                ex.Data["surname"] = surname;
                ex.Data["phone"] = phone;
                ex.Data["email"] = email;
                //ExceptionHandling.Handle(ex);
                throw;
            }
        }

        [WebMethod]
        public object Case_Save(DataObjects.NewCaseSaveInfo newCaseSaveInfo)
        {
            try
            {
                //TODO
                Auth.Check(PagesAuthorization.Pages.NewCase, Auth.AuthType.SecurityException);

                var userData = CacheManager.Users.Current;

                using (var db = new ICloudRepairEntities())
                {

                    if (newCaseSaveInfo.repairordernumber != null && newCaseSaveInfo.repairordernumber != string.Empty)
                    {
                        ECase cas = (from c in db.Case
                                     where c.RepairOrderNumber == newCaseSaveInfo.repairordernumber
                                           select c).FirstOrDefault()
                                   ;

                        fillCase(cas, newCaseSaveInfo, db);
                        cas.Customer = CreateOrUpdateCustomer(newCaseSaveInfo, db, userData);
                    }
                    else
                    {
                        ECase newCase = new ECase();
                        newCase.CaseId = Guid.NewGuid();
                        newCase.CaseTypeId = newCaseSaveInfo.casetypeid;
                        newCase.CreatedAt = DateTime.Now;
                        newCase.CreatedBy = userData.Id;
                        
                        newCase.PartnerId = userData.PartnerGuid;
                        newCase.RepairOrderNumber = RepairOrderNumber_Get();

                        fillCase(newCase, newCaseSaveInfo, db);

                        newCase.Customer = CreateOrUpdateCustomer(newCaseSaveInfo, db, userData);
                        
                        db.AddToCase(newCase);
                    }
                    db.SaveChanges();
                }
                return true;
            }
            catch (Exception ex)
            {
                //ex.Data["name"] = name;
                //ex.Data["surname"] = surname;
                //ex.Data["phone"] = phone;
                //ex.Data["email"] = email;
                //ExceptionHandling.Handle(ex);
                throw;
            }
        }

        private ECustomer CreateOrUpdateCustomer(DataObjects.NewCaseSaveInfo newCaseSaveInfo, 
            ICloudRepairEntities db, 
            UserCached userData
            )
        {

            if (newCaseSaveInfo.customerguid != null && newCaseSaveInfo.customerguid != string.Empty)
            {
                Guid existingGuid = Guid.Parse(newCaseSaveInfo.customerguid);
                ECustomer cust = (from c in db.Customers
                                  where c.GuidId == existingGuid
                                  select c).FirstOrDefault()
                           ;
                cust.Name = newCaseSaveInfo.customername;
                cust.Surname = newCaseSaveInfo.customersurname;
                cust.Phone = newCaseSaveInfo.customerphone;

                cust.Email = newCaseSaveInfo.customeremail;
                //newCase.Customer = cust;
                return cust;
            }
            else
            {

                ECustomer cust = new ECustomer();
                cust.GuidId = Guid.NewGuid();
                cust.PartnerId = userData.PartnerGuid;
                cust.Name = newCaseSaveInfo.customername;
                cust.Surname = newCaseSaveInfo.customersurname;
                cust.Phone = newCaseSaveInfo.customerphone;
                cust.Email = newCaseSaveInfo.customeremail;
                db.AddToCustomers(cust);
                //newCase.Customer = cust;
                return cust;
            }
        }

        private ECase fillCase(ECase newCase, DataObjects.NewCaseSaveInfo newCaseSaveInfo, ICloudRepairEntities db)
        {
            newCase.ModelGuid = Guid.Parse(newCaseSaveInfo.modelguid);
            var model = db.Model.Where(m => m.GuidId == newCase.ModelGuid).FirstOrDefault();

            newCase.Model = model.Name;
            model.ManufacturerReference.Loaded();

            newCase.Manufacturer = model.Manufacturer.Name;
            newCase.StatusId = 1;//TODO Hardcoded, change to  const;

            newCase.CaseDescription = newCaseSaveInfo.casedescription;


            newCase.EstimatedPrice = newCaseSaveInfo.estimatedprice;
            newCase.EstimatedDateCompletion = newCaseSaveInfo.estimateddatecompletion.FromClientDateStr();
            newCase.DateComplete = null;
            newCase.IMEI = newCaseSaveInfo.imei;
            newCase.DateCollected = DateTime.Now;
            newCase.Deposit = newCaseSaveInfo.deposit;
            newCase.DeviceConditionId = newCaseSaveInfo.DeviceConditionId;

            List<int> existingPhoneSetIdList= new List<int>();
            foreach (var i in db.CrossCasePhoneSet.Where(i => i.CaseId == newCase.CaseId).ToList())
            {
                existingPhoneSetIdList.Add(i.PhoneSetId);
                if (!newCaseSaveInfo.phoneSets.Contains(i.PhoneSetId))
                    db.DeleteObject(i);
            }



            foreach (int psId in newCaseSaveInfo.phoneSets)
            {
                if (!existingPhoneSetIdList.Contains(psId))
                {
                    ECrossCasePhoneSet phoneSet = new ECrossCasePhoneSet();
                    phoneSet.GuidId = Guid.NewGuid();
                    phoneSet.CaseId = newCase.CaseId;
                    phoneSet.PhoneSetId = psId;
                    db.AddToCrossCasePhoneSet(phoneSet);
                }
            }

            return newCase;
        }

        [WebMethod]
        public object Cases_GetHistory(DataObjects.Grid grid)
        {
            try {
                //TODO
                Auth.Check(PagesAuthorization.Pages.NewCase, Auth.AuthType.SecurityException);

                using (ICloudRepairEntities db = new ICloudRepairEntities()) 
                {
                    return null;
                }
            }
            catch (Exception ex) {
                ex.Data["grid"] = grid.JSON_SerializeEx();
                //ExceptionHandling.Handle(ex);
                throw;
            }
        }

        private IQueryable<ECase> getPrepareObjectByCriteria(ICloudRepairEntities db, CaseSearch criteria)
        {
            var userData = CacheManager.Users.Current;
            IQueryable<ECase> cas = db.Case;

            cas = cas.Where(i => i.PartnerId == userData.PartnerGuid);

            if (criteria.SerialNumber.TrimNull() != null)
            {
                cas = cas.Where(i => i.IMEI.ToLower().Contains(criteria.SerialNumber.Trim().ToLower())); 
            }
            if (criteria.CaseNumber.TrimNull() != null)
            {
                cas = cas.Where(i => i.RepairOrderNumber.ToLower().Contains(criteria.CaseNumber.Trim().ToLower()));
            }

            //if (criteria.RadDatePickerBIFromDate.Value == 0)
            //{
            //    criteria.RadDatePickerBIFromDate.ToClientTime().CDateToStr();
            //    //Overdue
            //    trans = trans.Where(i => (i.ServicePartnerDeadline < DateTime.Now) || (i.CustomerDeadline.Value < DateTime.Now));
            //}
            return cas;
        }

        [WebMethod]
        public object Cases_Search(CaseSearch criteria, DataObjects.Grid grid)
        {
            try
            {
                Auth.Check(PagesAuthorization.Pages.NewCase, Auth.AuthType.SecurityException);

                

                using (ICloudRepairEntities db = new ICloudRepairEntities())
                {
                    var userData = CacheManager.Users.Current;

                    IQueryable<ECase> cases = getPrepareObjectByCriteria(db, criteria);

                    IQueryable<ECase> items = cases.OrderByDescending(i => i.RepairOrderNumber); ;
                    items = items.Sort(grid.Sort,
                        items.CreateSortField("CustomerName", i => i.Customer.Name),
                        items.CreateSortField("CustomerSurname", i => i.Customer.Surname),
                        items.CreateSortField("CustomerPhone", i => i.Customer.Phone),
                        items.CreateSortField("Imei", i => i.IMEI),
                        items.CreateSortField("EstimatedPrice", i => i.EstimatedPrice),
                        items.CreateSortField("EstimatedDate", i => i.EstimatedDateCompletion)
                    );
                    var aa = items.ToList();
                    return new WSResult<object>
                    {
                        Success = true,
                        Data = new
                        {
                            Count = items.Count(),
                            Items = items.Select(c =>
                                new
                                {
                                    RowGuid = c.CaseId,
                                    RepairOrderNumber = c.RepairOrderNumber,
                                    CustomerName = c.Customer.Name,
                                    CustomerSurname = c.Customer.Surname,
                                    CustomerPhone = c.Customer.Phone,
                                    EstimatedPrice = c.EstimatedPrice,
                                    EstimatedDateCompletion = c.EstimatedDateCompletion,
                                    ProblemDescription = c.CaseDescription.Length > 15 ? c.CaseDescription.Substring(0, 15) + "..." : c.CaseDescription,
                                }).Skip(grid.StartIndex).Take(grid.PageSize).Postprocess(c => new
                                {
                                    c.RowGuid,
                                    c.RepairOrderNumber,
                                    EstimatedDateCompletion = c.EstimatedDateCompletion.CDateToStrDay(),
                                    c.CustomerName,
                                    c.CustomerSurname,
                                    c.CustomerPhone,
                                    c.ProblemDescription,
                                    c.EstimatedPrice
                                }).ToList()
                        }
                    };
                }
            }
            catch (Exception ex)
            {
                ex.Data["criteria"] = criteria.JSON_SerializeEx();
                ex.Data["grid"] = grid.JSON_SerializeEx();
                throw;
            }
        }

        private string GetModelFullname(EModel mod)
        {
            return mod.Manufacturer.Name.Replace(" ", "") + " " + mod.Name.Replace(" ", "");
        }

        private string RepairOrderNumber_Get()
        {
            Auth.Check(PagesAuthorization.Pages.NewCase, Auth.AuthType.SecurityException);

            var userData = CacheManager.Users.Current;

            using (ICloudRepairEntities db = new ICloudRepairEntities())
            {
                var partner = db.Partners.Where(p => p.PartnerId == userData.PartnerGuid).FirstOrDefault();
                if (partner.RepairOrderCountUpdate.Value.Year > DateTime.Now.Year
                    || partner.RepairOrderCountUpdate.Value.Month > DateTime.Now.Month
                    || partner.RepairOrderCountUpdate.Value.Day > DateTime.Now.Day)
                {
                    partner.RepairOrderCount = 0;
                    partner.RepairOrderCountUpdate = DateTime.Now;
                }
                else
                    partner.RepairOrderCount++;
                db.SaveChanges();

                string RepairOrderNumber = userData.Login + "_" + string.Format("{0:yyyyMMdd}", DateTime.Now) + "_" + partner.RepairOrderCount.ToString();
                return RepairOrderNumber;
            }
        }
    }
}
